/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.chipchip.codec;

import com.chipchip.objects.CCMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/**
 *
 * @author Tri
 */
public class MessageEncoder extends MessageToByteEncoder<CCMessage> {

    @Override
    protected void encode(ChannelHandlerContext ctx, CCMessage msg, ByteBuf out) throws Exception {
        try {
            byte[] data = msg.getBuffer();
            int dataLength = data.length;

            // Write a message.
            out.writeInt(dataLength + 4);  // data length
            out.writeByte(msg.id); // command
            out.writeBytes(data);      // data
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
